package top.zhangjianyong.tools.service.etf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.zhangjianyong.tools.entity.ETF;
import top.zhangjianyong.tools.entity.ETFData;
import top.zhangjianyong.tools.service.mybatis.IETFDataService;
import top.zhangjianyong.tools.utils.HolidayUtil;
import top.zhangjianyong.tools.utils.SoHuETFUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
import java.util.List;

import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME;

@Service
public class SohuETFServiceImpl implements ETFService {
    @Autowired
    private HolidayUtil holidayUtil;
    @Autowired
    private IETFDataService ietfDataService;

    @Override
    public ETF getETF(String code) {
        SoHuETFUtil.SoHuETF etf = SoHuETFUtil.getETF(code);
        if (null == etf) return null;
        return createETF(etf);
    }

    private ETF createETF(SoHuETFUtil.SoHuETF soHuETF) {
        ETF etf = new ETF();
        etf.setCode(soHuETF.getCode());
        etf.setValue(new BigDecimal(soHuETF.getValue()));
        LocalTime time = LocalTime.parse(soHuETF.getTime());
        LocalDate date = LocalTime.now().isBefore(time)
                ? holidayUtil.lastStock(LocalDate.now()) :
                holidayUtil.lastOrCurrentStock(LocalDate.now());
        etf.setValueDate(LocalDateTime.of(date, time));


        ETFData etfData = ietfDataService.lastOne(soHuETF.getCode());
        if (etfData!=null){ //第一次创建的是否会没有历史数据
            BigDecimal lastValue = etfData.getValue();
            BigDecimal value = new BigDecimal(soHuETF.getValue());
            BigDecimal rate = value.subtract(lastValue).divide(lastValue, 4, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100));
            etf.setDailyRate(rate);
        }
        return etf;
    }


    @Override
    public ETFData getETFDate(String code, int time) {
        return null;
    }

    @Override
    public List<ETFData> getRecords(String code) throws Exception {
        return Collections.emptyList();
    }

    @Override
    public List<ETFData> getRecords(int page, String code) throws ParseException {
        return Collections.emptyList();
    }
}
